import { defineStore } from 'pinia';
import { RouterView } from 'vue-router';
import { NstdMessage } from 'nstd-components-pc-v3';
import { asyncRouters } from '@/router/routes';
import { setAuthorization, setUserInfo, removeAuthorization } from '@/utils/auth';
import { getClientMenuTreeByRoleAndApplication, getSignV2Logout } from '@/api/auth/signV2.js';
import { menu } from '../../../public/menu';
const BaseLayout = () => {
  return h(RouterView);
};
BaseLayout.displayName = 'BaseLayout';

const allVueFile = import.meta.glob('/src/views/**/*.vue');
const layoutVlayoutueFile = import.meta.glob('/src/layout/**/*.vue');

const generatorDynamicRouterByUserRouter = (routers) => {
  return routers.map((routerItem) => {
    const itemTem = {
      path: routerItem.menuUrl,
      meta: {
        ...routerItem,
        title: routerItem.menuName,
        display: routerItem.display,
        nav: routerItem.display,
        menuType: routerItem.menuType
      },
      name: routerItem.menuCode,
      component:
        routerItem.menuType === 2
          ? allVueFile[`/src/views${routerItem.menuUrl}.vue`]
          : (layoutVlayoutueFile[`/src/layout/${routerItem.routerTemplateName}.vue`] ?? BaseLayout)
    };
    if (routerItem.children && routerItem.children.length) {
      itemTem.children = generatorDynamicRouterByUserRouter(routerItem.children);
    }
    return itemTem;
  });
};

export const useAuthStore = defineStore('auth-store', {
  state: () => {
    return {
      userInfo: {},
      token: '',
      routers: asyncRouters,
      isRequest: false, // 是否请求过路由
      addRouters: [],
      menuList: []
    };
  },
  actions: {
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
      setUserInfo(userInfo);
      // 顺便把token存起来
      this.setToken(userInfo.accessToken);
    },
    setToken(token) {
      this.token = token;
      setAuthorization(token);
    },
    clearUserInfo() {
      this.userInfo = {};
      this.token = '';
      removeAuthorization();
    },
    generateRoutes(roleId) {
      return new Promise((resolve, reject) => {
        const filterTreeArray = (tree, num) => {
          return tree
            .filter((item) => {
              return item.display === 0 || item.display === 1;
            })
            .map((item) => {
              item = Object.assign({}, item);
              if (item.children) {
                item.children = filterTreeArray(item.children, num);
              }
              return item;
            });
        };
        if (menu.length) {
          const data = menu;
          // display = 1是子页面,display = 0 不是子页面
          const menuData = filterTreeArray(data[0].children, 0) || [];
          const otherData = filterTreeArray(data[0].children, 1) || [];
          const dynamicRoutes = generatorDynamicRouterByUserRouter(menuData);
          this.menuList = [...asyncRouters, ...dynamicRoutes];
          this.addRouters = [...dynamicRoutes, ...generatorDynamicRouterByUserRouter(otherData)];
          this.isRequest = true;
          resolve();
        } else {
          getClientMenuTreeByRoleAndApplication({
            application: window.NC_PROJECT_CONFIG.application,
            projectName: window.NC_PROJECT_CONFIG.projectName,
            roleId
          })
            .then(async (res) => {
              const { data, code, msg } = res;
              if (code === 200) {
                if (data && data.length) {
                  // display = 1是子页面,display = 0 不是子页面
                  const menuData = filterTreeArray(data[0].children, 0) || [];
                  const otherData = filterTreeArray(data[0].children, 1) || [];
                  const dynamicRoutes = generatorDynamicRouterByUserRouter(menuData);
                  this.menuList = [...asyncRouters, ...dynamicRoutes];
                  this.addRouters = [...dynamicRoutes, ...generatorDynamicRouterByUserRouter(otherData)];
                  this.isRequest = true;
                  resolve();
                } else {
                  await getSignV2Logout();
                  sessionStorage.setItem('Authorization', '');
                  sessionStorage.setItem('userInfo', '');
                  this.clearUserInfo();
                  reject(msg);
                  NstdMessage({
                    message: '暂无配置菜单！',
                    type: 'error',
                    duration: 3 * 1000
                  });
                }
              } else {
                reject(new Error());
              }
            })
            .catch((e) => {
              reject(e);
            });
        }
      });
    }
  }
});
